import api from '../../api'
import { setLocalStorage } from '@/common/utils/local-storage'
import Vue from 'vue'

// initial state
// shape: [{ id, quantity }]
const state = {
  items: localStorage.getItem('cartItems') ? JSON.parse(localStorage.getItem('cartItems')) : [],
  checkoutStatus: null,
  // checkedAll: false,
  checkedItems: []
}

// getters
const getters = {
  numberOfCartItem (state, getters) {
    return state.items.reduce((total, item) => total + item.quantity, 0)
  },
  checkedItems (state, getters) {
    return state.items.filter(item => item.checked).map(item => item.product.id)
  },
  checkedAllFlag (state, getters) {
    return state.items.filter(item => item.checked).length === state.items.length
  },
  totalPrice () {
    const selectedItems = state.items.filter(item => item.checked)
    if (selectedItems && selectedItems.length > 0) {
      return selectedItems.reduce((total, item) => total + 100 * item.product.price * item.quantity, 0)
    } else {
      return 0.00
    }
  }
}

// actions
const actions = {
  async checkout ({ commit, state }, params) {
    const savedCartItems = [...state.items]
    const unselectedItems = [...state.items].filter(item => item.checked === false)
    commit('setCheckoutStatus', null)
    // empty cart
    commit('setCartItems', { items: unselectedItems })
    const { data } = await api.order.orderCreate(params)
    if (data.code === 200) {
      commit('setCheckoutStatus', 'successful')
    } else {
      commit('setCheckoutStatus', 'failed')
      commit('setCartItems', { items: savedCartItems })
    }
  },
  async refreshCart ({ commit, state }, params) {
    const { data } = await api.product.productList(params)
    if (data.code === 200) {
      data.data.forEach(product => commit('updateItem', product))
    }
  },
  addProductToCart ({ state, commit }, product) {
    console.log('in addProductToCart')
    console.log(product)
    commit('setCheckoutStatus', null)
    if (product.inventory > 0) {
      const cartItem = state.items.find(item => item.product.id === product.id)
      if (!cartItem) {
        commit('pushProductToCart', { product: product })
      } else {
        commit('incrementItemQuantity', { id: cartItem.product.id })
      }
    }
  }
}

// mutations
const mutations = {
  pushProductToCart (state, { product }) {
    state.items.push({
      product,
      checked: true,
      quantity: 1
    })
    setLocalStorage({ cartItems: JSON.stringify(state.items) })
  },

  deleteProductFromCart (state, productId) {
    state.items = state.items.filter(item => item.product.id !== productId)
    setLocalStorage({ cartItems: JSON.stringify(state.items) })
  },

  toggleCheckedAll (state) {
    const flag = state.items.filter(item => item.checked).length === state.items.length
    console.log(flag)
    for (let item of state.items) {
      item.checked = !flag
    }
    setLocalStorage({ cartItems: JSON.stringify(state.items) })
  },

  changeSelected (state, selected) {
    state.items.forEach((item, index) => {
      Vue.set(state.items[index], 'checked', false)
    })
    state.items.filter(item => selected.includes(item.product.id)).forEach((item, index) => {
      Vue.set(state.items[index], 'checked', true)
    })
    setLocalStorage({ cartItems: JSON.stringify(state.items) })
  },

  incrementItemQuantity (state, { id }) {
    let cartItem = state.items.find(item => item.product.id === id)
    if (cartItem) {
      cartItem.quantity++
      cartItem.checked = true
      setLocalStorage({ cartItems: JSON.stringify(state.items) })
    }
  },

  updateItem (state, product) {
    const cartItem = state.items.find(item => item.product.id === product.id)
    if (cartItem) {
      cartItem.product = product
      setLocalStorage({ cartItems: JSON.stringify(state.items) })
    }
  },

  setCartItems (state, { items }) {
    state.items = items
    setLocalStorage({ cartItems: JSON.stringify(state.items) })
  },

  setCheckoutStatus (state, status) {
    state.checkoutStatus = status
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
